package com.vlong.town.util.listener;

import com.vlong.town.util.common.TownConstant;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

/**
 * TownWeb监听
 * @author Assassin
 */
@WebListener
public class TownWebContextListener implements ServletContextListener {

    // Fields

    private static Log logger = LogFactory.getLog(TownWebContextListener.class);// 日志记录
    @Autowired
    private WebApplicationContext applicationContext;// WebApplicationContext

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 查询系统存在的URI路径集合
        TownConstant.SYSTEM_URIS = new ArrayList<String>();
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo,HandlerMethod> map = mapping.getHandlerMethods();
        for (RequestMappingInfo info : map.keySet()){
            Set<String> patterns = info.getPatternsCondition().getPatterns();
            for (String uri : patterns){
                TownConstant.SYSTEM_URIS.add(uri);
            }
        }
        logger.info("Town Web Initialized，Controller Mapping => " + TownConstant.SYSTEM_URIS.size());
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        logger.info("Town Web Destroyed");
    }

}